<?php
/**
 * 财务系统服务
 */

namespace App\Services\Tools;

use App\Enums\FinancialEnum;
use App\Exceptions\BasicException;
use GuzzleHttp\Client;
use Exception;
use Illuminate\Support\Facades\Log;

class FinancialService
{
    private $host; // 财务系统域名

    private $appKey; // 财务系统APP_KEY

    private $appSecret; // 财务系统APP_SECRET

    private $timeout; //  请求超时时间

    private $httpClient;

    public function __construct()
    {
        $this->host = env('FINANCIAL_HOST');
        $this->appKey = env('FINANCIAL_APP_KEY');
        $this->appSecret = env('FINANCIAL_APP_SECRET');
        $this->timeout = env('FINANCIAL_TIMEOUT') ?? 30;
        if (empty($this->appKey) || empty($this->appSecret) || empty($this->host)) {
            throw new BasicException(0, '财务系统未配置，请联系客服');
        }
        $this->httpClient = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);
    }
    /**
     * 同步提现数据
     * @param $params
     * @return bool|mixed
     * @author yangwenjie
     * @date 2022/4/8
     */
    public function syncWithdrawData($params)
    {
        $config = FinancialEnum::FINANCIAL_SYSTEM_SYNC_WITHDRAW;
        $params = [
            'form' => json_encode($params)
        ];
        return $this->financialRequest($config['path'], $config['method'], $params);
    }

    /**
     * 获取充值退款信息详情
     * @param $params
     * @return bool|mixed
     * @author wangzefei
     * @date 2022/4/8
     */
    public function payRechargeRefundDetail($params)
    {
        $config = FinancialEnum::PAY_RECHARGE_REFUND_DETAIL;
        
        return $this->financialRequest($config['path'], $config['method'], $params,true);
    }

    /**
     * 充值退款操作
     * @param $params
     * @return bool|mixed
     * @author wangzefei
     * @date 2022/4/8
     */
    public function payRechargeRefund($params)
    {
        $config = FinancialEnum::PAY_RECHARGE_REFUND;

        return $this->financialRequest($config['path'], $config['method'], $params,true);
    }

    /**
     * 校验支付宝信息
     * @param $params
     * @return bool|mixed
     */
    public function syncCheckAliPayInfo($params)
    {
        $config = FinancialEnum::FINANCIAL_CHECK_ALIPAY_CARD;
        return $this->financialRequest($config['path'], $config['method'], $params);
    }

    /**
     * 生成签名
     * @param $params
     * @return string
     * @author yangwenjie
     * @date 2022/4/1
     */
    public function generateSign($params)
    {
        $keys = array_keys($params);
        arsort($keys);
        $str = '';
        foreach ($keys as $key) {
            $str .= $key . $params[$key];
        }

        $str .= $this->appSecret;
        $sign = md5($str);
        return $sign;
    }

    public function getHeader($params)
    {
        $timestamp = time();
        $params['timestamp'] = $timestamp;
        $params['appkey'] = $this->appKey;
        $sign = $this->generateSign($params);
        $result['timestamp'] = $timestamp;
        $result['sign'] = $sign;
        $result['appkey'] = $this->appKey;
        $result['Content-Type'] = "application/json";
        return $result;
    }

    /**
     * 发起财务系统请求
     * @param $path
     * @param $method
     * @param $params
     * @return bool|mixed
     * @author yangwenjie
     * @date 2022/4/8
     */
    public function financialRequest($path, $method, $params,$is_message=false)
    {
        $headers = $this->getHeader($params);
        $result = false;
        try {
            if (strtolower($method) == 'post') {
                $financial_res = $this->httpPost($path, $params, $headers);
            } else {
                $financial_res = $this->httpGet($path, $params, $headers);
            }
            if (!empty($financial_res)) {
                $financial_res = json_decode($financial_res, true);
                if ($financial_res['code'] == 200) {
                    $result = $financial_res;
                } else {
                    throw new BasicException(0, '财务系统错误msg：' . $financial_res['message']);
                }
            } else {
                throw new BasicException(0, '没有请求成功，状态码不是200');
            }
        } catch (Exception $e) {
            Log::info('=====财务系统请求错误=====||' . $e->getMessage() . json_encode($params));
            if($is_message){
                return  $financial_res['message'];
            }
            return false;
        }
        return $result;
    }


    public function httpPost($path, $params, $headers, $auth = '')
    {
        $options = [
            "headers" => $headers,
            "body" => json_encode($params),
            "auth" => $auth,
        ];
        $response = $this->httpClient->request('POST', $path, $options);
        if (200 == $response->getStatusCode()) {
            // echo $response->getBody();
            return $response->getBody();
        } else {
            // 请求失败返回空
            return "";
        }
    }

    public function httpGet($path, $params, $headers = [])
    {
        $options = [
            "query" => $params,
            "headers" => $headers,
        ];
        $response = $this->httpClient->request('GET', $path, $options);
        if (200 == $response->getStatusCode()) {
            return $response->getBody();
        }
    }
}